﻿using Microsoft.AspNetCore.DataProtection;
using Microsoft.IdentityModel.Tokens;
using RuoVea.ExJwtBearer;
using RuoVea.OAuthServer.Model;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;

namespace RuoVea.OAuthServer.Server;

/// <summary>
/// IOAuthServers
/// </summary>
public class IOAuthServers
{
    private readonly IJwtHelper _jwtHelper;
    public IDataProtectionProvider _provider;

    public IOAuthServers(IDataProtectionProvider provider, IJwtHelper jwtHelper   )
    {
        _provider = provider;
        _jwtHelper = jwtHelper;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="code">code解析值</param>
    /// <param name="codeVerfy">地址传参值</param>
    /// <returns></returns>
    public bool ValidateCode(CodeInfoModel code, string codeVerfy)
    {
        var sha256 = SHA256.Create();
        var codeVery = Base64UrlEncoder.Encode(sha256.ComputeHash(Encoding.ASCII.GetBytes(codeVerfy)));
        return codeVery.Equals(code.CodeChallenge);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="userId"></param>
    /// <param name="score"></param>
    /// <returns></returns>
    public string IssueToken(string userId ,string score)
    {
        Dictionary<string, object> issueUser = IssueUser(userId);

        if (issueUser == null )
            throw new Exception("缺少必要信息.");

        if(!issueUser.Select(x=>x.Key).ToList().Contains(ClaimTypes.Sid))
            throw new Exception("缺少sid信息.");

        if (!string.IsNullOrWhiteSpace(score))
            issueUser.Add("scope", score.Split(','));

        return _jwtHelper.Encrypt(issueUser);
    }

    public virtual Dictionary<string, object> IssueUser(string userId) {
        return null;
    }

}
